// 内存缓存管理器

interface CacheItem<T> {
  data: T
  timestamp: number
  ttl: number
}

export class MemoryCacheManager {
  private cache = new Map<string, CacheItem<any>>()
  private readonly DEFAULT_TTL = 5 * 60 * 1000 // 5分钟
  private readonly MAX_CACHE_SIZE = 1000 // 最大缓存条目数
  private cleanupInterval: NodeJS.Timeout | null = null

  constructor() {
    // 每5分钟清理一次过期缓存
    this.cleanupInterval = setInterval(() => {
      this.cleanupExpired()
    }, 5 * 60 * 1000)
  }

  // 设置缓存
  async set(key: string, value: any, ttl: number = this.DEFAULT_TTL): Promise<void> {
    // 如果缓存已满，删除最旧的条目
    if (this.cache.size >= this.MAX_CACHE_SIZE) {
      const firstKey = this.cache.keys().next().value
      if (firstKey) {
        this.cache.delete(firstKey)
      }
    }

    this.cache.set(key, {
      data: value,
      timestamp: Date.now(),
      ttl
    })
  }

  // 获取缓存
  async get<T>(key: string): Promise<T | null> {
    const cached = this.cache.get(key)
    if (!cached) return null

    // 检查是否过期
    if (Date.now() - cached.timestamp > cached.ttl) {
      this.cache.delete(key)
      return null
    }

    return cached.data
  }

  // 删除缓存
  async del(key: string): Promise<void> {
    this.cache.delete(key)
  }

  // 批量删除缓存（通过模式匹配）
  async delPattern(pattern: string): Promise<void> {
    const regex = new RegExp(pattern.replace(/\*/g, '.*'))
    const keysToDelete: string[] = []
    
    for (const key of this.cache.keys()) {
      if (regex.test(key)) {
        keysToDelete.push(key)
      }
    }
    
    keysToDelete.forEach(key => this.cache.delete(key))
  }

  // 检查缓存是否存在
  async exists(key: string): Promise<boolean> {
    const cached = this.cache.get(key)
    if (!cached) return false
    
    // 检查是否过期
    if (Date.now() - cached.timestamp > cached.ttl) {
      this.cache.delete(key)
      return false
    }
    
    return true
  }

  // 设置缓存过期时间
  async expire(key: string, ttl: number): Promise<void> {
    const cached = this.cache.get(key)
    if (cached) {
      cached.ttl = ttl
      cached.timestamp = Date.now()
    }
  }

  // 获取缓存剩余过期时间
  async ttl(key: string): Promise<number> {
    const cached = this.cache.get(key)
    if (!cached) return -1
    
    const remaining = cached.ttl - (Date.now() - cached.timestamp)
    return remaining > 0 ? Math.floor(remaining / 1000) : -1
  }

  // 生成用户相关的缓存键
  static getUserCacheKey(userId: string, type: string): string {
    return `user:${userId}:${type}`
  }

  // 生成书签相关的缓存键
  static getBookmarksCacheKey(userId: string): string {
    return `bookmarks:${userId}`
  }

  // 清理用户相关的所有缓存
  async clearUserCache(userId: string): Promise<void> {
    await this.delPattern(`user:${userId}:*`)
    await this.delPattern(`bookmarks:${userId}*`)
  }

  // 清理过期缓存
  private cleanupExpired(): void {
    const now = Date.now()
    const keysToDelete: string[] = []
    
    for (const [key, cached] of this.cache.entries()) {
      if (now - cached.timestamp > cached.ttl) {
        keysToDelete.push(key)
      }
    }
    
    keysToDelete.forEach(key => this.cache.delete(key))
    
    if (keysToDelete.length > 0) {
      console.log(`清理了 ${keysToDelete.length} 个过期缓存条目`)
    }
  }

  // 获取缓存统计
  getStats(): { size: number; maxSize: number; hitRate?: number } {
    return {
      size: this.cache.size,
      maxSize: this.MAX_CACHE_SIZE
    }
  }

  // 清空所有缓存
  async clear(): Promise<void> {
    this.cache.clear()
  }

  // ping方法
  async ping(): Promise<string> {
    return 'PONG'
  }

  // 清理资源
  destroy(): void {
    if (this.cleanupInterval) {
      clearInterval(this.cleanupInterval)
      this.cleanupInterval = null
    }
    this.cache.clear()
  }
}

// 导出单例实例
export const memoryCacheManager = new MemoryCacheManager()

// 缓存管理器
export class CacheManager {
  private static cache = memoryCacheManager

  static async set(key: string, value: any, ttl: number = 300): Promise<void> {
    await this.cache.set(key, value, ttl * 1000) // 转换为毫秒
  }

  static async get<T>(key: string): Promise<T | null> {
    return await this.cache.get<T>(key)
  }

  static async del(key: string): Promise<void> {
    await this.cache.del(key)
  }

  static async delPattern(pattern: string): Promise<void> {
    await this.cache.delPattern(pattern)
  }

  static async exists(key: string): Promise<boolean> {
    return await this.cache.exists(key)
  }

  static async expire(key: string, ttl: number): Promise<void> {
    await this.cache.expire(key, ttl * 1000) // 转换为毫秒
  }

  static async ttl(key: string): Promise<number> {
    return await this.cache.ttl(key)
  }

  static getUserCacheKey(userId: string, type: string): string {
    return MemoryCacheManager.getUserCacheKey(userId, type)
  }

  static getBookmarksCacheKey(userId: string): string {
    return MemoryCacheManager.getBookmarksCacheKey(userId)
  }

  static async clearUserCache(userId: string): Promise<void> {
    await this.cache.clearUserCache(userId)
  }
}

export default memoryCacheManager